// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()

  try {
    let users = await db.collection('user').where({
      openid: wxContext.OPENID
    }).field({
      _id: true,
      name: true,
      stuNo: true,
      school: true,
      tel: true,
      email: true,
      classes: true,
      openid: true
    }).get()
    console.log(users)
  


    if (users && users.data.length > 0) {
      return users.data[0]
    }

    console.log("------------add-------------------------")
    let userInfo = {
      name: "",
      stuNo: "",
      school: "",
      tel: "",
      email: "",
      classes: [],
      openid: wxContext.OPENID
    };


    let add_res = await db.collection('user').add({
      data: userInfo
    })

    userInfo._id = add_res._id
    console.log(add_res, add_res._id, userInfo)
    return userInfo

  } catch (e) {
    console.log(e)
  }
}